package com.lx.boot.web.filter;

import com.lx.annotation.Note;
import com.lx.boot.OS;
import com.lx.entity.Var;
import com.lx.util.LX;
import com.lx.util.secure.algorithm.coder.CoderType;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

import static com.lx.constant.DefaultBaseConstant.AUTHORIZATION;

@Slf4j
@Note("默认不进行参数加解密")
@Component("md5ApiFilter")
public class Md5ApiFilter extends ApiEncryptFilter {

    @Override
    protected RequestWrapper getRequestWrapper(HttpServletRequest request , byte[] bodys, boolean notEncryptionUrl) throws IOException {
        if (!isPostOrPut(request) || notEncryptionUrl){
            return new RequestWrapper(request, bodys);
        }
        String dataJson = new String(bodys, StandardCharsets.UTF_8);
        LX.exObj(dataJson , "签名验证失败,没有入参");
        if (!dataJson.startsWith("{")){
            LX.exMsg("POST参数需要加密时 body消息需要是json对象形式!");
        }
        Var map = LX.toMap(dataJson);
        String timestamp = map.getStr("timestamp");
        String nonce = map.getStr("nonce");
        checkApiTimeAndRepeat(timestamp,nonce);
        String sign = map.getStr("sign");
        String token = request.getHeader(AUTHORIZATION);
        map.put("token",token);
        String s = LX.md5(LX.createLinkString(map));
        LX.exMsg(!sign.equalsIgnoreCase(s), "方法签名认证失败! 请检查签名是否正确:"+s);
        String data = map.getStr("data");
        if (LX.isEmpty(data)){
            return new RequestWrapper(request, bodys);
        }
        byte[] reqBodyBytes = CoderType.BASE64.decode(data);
        log.info("url==>{} 实际请求参数:{}",request.getServletPath() ,LX.byteArrayToString(reqBodyBytes,5000));
        return new RequestWrapper(request, reqBodyBytes);
    }
}
